<?php
/*
File: auctions.php
Version: 2.0
Date created: 
Last Edited : 26-07-2008
Author: Craig G Smith<craig@joomla-host.co.za
*/

  defined( 'JOSCOM_VERSION' ) or die( 'Direct Access to this location is not allowed.' );
  if (defined( '_OSCOMMERCE_LOADED' )) {
    if (!DB_SHARED) {
      tep_db_connect() or die('Unable to connect to database server!');
    }
    global $category_links, $languages_id, $cPath, $cPath_array, $current_category_id;
    global $request_type, $lng, $cart, $currencies, $language, $navigation, $breadcrumb;
  } else {
    require(DIR_WS_COMPONENT . 'includes/application_top.php');
  }
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new currencies();

  $action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');

  if (tep_not_null($action)) {
    switch ($action) {
      case 'setflag':
        tep_set_auctions_status($_REQUEST['id'], $_REQUEST['flag']);

        tep_redirect(tep_href_link(FILENAME_AUCTIONS_PRODUCTS, (isset($_REQUEST['page']) ? 'page=' . $_REQUEST['page'] . '&' : '') . 'aID=' . $_REQUEST['id'], 'NONSSL'));
        break;
      case 'insert':
        $products_id = tep_db_prepare_input($_REQUEST['products_id']);
        $products_price = tep_db_prepare_input($_REQUEST['products_price']);
        $auctions_price = tep_db_prepare_input($_REQUEST['auctions_price']);
		$overbid_amount = tep_db_prepare_input($_REQUEST['overbid_amount']);	
        $expires = tep_db_prepare_input(DATE("Y-m-d H:i:s", strtotime($_REQUEST['day'])));

        if (substr($auctions_price, -1) == '%') {
          $new_auction_insert_query = tep_db_query("select products_id, products_price from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
          $new_auction_insert = tep_db_fetch_array($new_auction_insert_query);

          $products_price = $new_auction_insert['products_price'];
          $auctions_price = ($products_price - (($auctions_price / 100) * $products_price));
        }

        $expires_date = $expires;


        tep_db_query("insert into " . TABLE_AUCTIONS_PRODUCTS . " (products_id, auctions_starting_price, auctions_date_added, expires_date, status,overbid_amount ) values ('" . (int)$products_id . "', '" . tep_db_input($auctions_price) . "', now(), '" . tep_db_input($expires_date) . "', '1','".tep_db_input($overbid_amount)."')");

        tep_redirect(tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page']));
        break;
      case 'update':
        $auctions_id = tep_db_prepare_input($_REQUEST['auctions_id']);
        $products_price = tep_db_prepare_input($_REQUEST['products_price']);
        $auctions_price = tep_db_prepare_input($_REQUEST['auctions_price']);


        $expires = tep_db_prepare_input(DATE("Y-m-d H:i:s", strtotime($_REQUEST['day'])));


        if (substr($auctions_price, -1) == '%') $auctions_price = ($products_price - (($auctions_price / 100) * $products_price));



        tep_db_query("update " . TABLE_AUCTIONS_PRODUCTS . " set auctions_starting_price = '" . tep_db_input($auctions_price) . "', auctions_last_modified = now(), expires_date = '" . tep_db_input($expires) . "' where auctions_id = '" . (int)$auctions_id . "'");

        tep_redirect(tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $auctions_id));
        break;
      case 'deleteconfirm':
      //die();
        $auctions_id = tep_db_prepare_input($_REQUEST['aID']);

        tep_db_query("delete from " . TABLE_AUCTIONS_PRODUCTS . " where auctions_id = '" . (int)$auctions_id . "'");

        tep_redirect(tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page']));
        break;
		
	case 'accept_bid':
		$customers_id	=$_GET['customers_id'];
		$sql_auction	=	'select a.products_id, bid_price from '.TABLE_AUCTIONS_BIDS." ab, ".TABLE_AUCTIONS_PRODUCTS." a where a.auctions_id=ab.auctions_id and a.auctions_id='".$aID."' and customers_id='".(int)$customers_id."' ";
		$auction_info	=	tep_db_fetch_array(tep_db_query($sql_auction));	
		
		// insert the auction bid to the customer's basket 
		$sql_insert	=	'insert into '. TABLE_CUSTOMERS_BASKET." (customers_basket_id, customers_id, products_id, customers_basket_quantity, final_price, customers_basket_date_added) values ('','$customers_id','".$auction_info['products_id']."','1','".$auction_info['bid_price']."','".date('Ymd')."') ";
		if( tep_db_query($sql_insert) ) {
			// update auction bid statused 
			$sql_update	=	'update '.TABLE_AUCTIONS_BIDS." set bid_status	='won' where auctions_id='".$aID."' and customers_id='".$customers_id."'";		
			tep_db_query($sql_update);
			// send email to this customer about auction won regarding
			$sql_customer	=	'select customers_lastname, customers_firstname,customers_email_address from '.TABLE_CUSTOMERS." where customers_id= '".$customers_id."'";
			
			$customer_info	=	tep_db_fetch_array(tep_db_query($sql_customer));
			$customer_firstname	=	$customer_info['customer_firstname'];
			$customer_lastname	=	$customer_info['customers_lastname'];
			$customer_email		=	$customer_info['customers_email_address'];
			$customer_name	=	$customer_firstname	.' '.$customer_lastname;
			$auction_url	=	tep_catalog_href_link(FILENAME_PRODUCT_INFO,'products_id='.$auction_info['products_id']);
			
			$email_text	=	str_replace('[customer_firstname]',$customer_firstname,str_replace('[customer_lastname]',$customer_lastname,str_replace('[customer_email]',$customer_email,str_replace('[auction_name]',$auction_name,str_replace('[auction_url]',$auction_url,AUCTION_WON_EMAIL)))));
	
			tep_mail($customer_name, $customer_email, AUCTION_WON_EMAIL_SUBJECT, $email_text, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
			
			
			
		}
		

		break;
    }
  }
?>

<link rel="stylesheet" type="text/css" href="<?php echo DIR_WS_COMPONENT ?>includes/stylesheet.css">
<script language="javascript" src="<?php echo DIR_WS_COMPONENT ?>includes/general.js"></script>
<?php
  if ( ($action == 'new') || ($action == 'edit') ) {
?>

<link rel="stylesheet" type="text/css" href="<?php echo DIR_WS_COMPONENT ?>includes/javascript/calendar.css">

<script language="JavaScript" src="<?php echo DIR_WS_COMPONENT ?>includes/javascript/aucal.js"></script>
<?php
  }
?>
</head>
<body  onLoad="SetFocus();">
<div id="popupcalendar" class="text"></div>
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2" class="adminlist">
  <tr>
    
    <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
        <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <th class="pageHeading"><?php echo HEADING_TITLE; ?></td>
            <th class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
          </tr>
        </table></td>
      </tr>
<?php
  if ( ($action == 'new') || ($action == 'edit') ) {
    $form_action = 'insert';
    if ( ($action == 'edit') && isset($_REQUEST['aID']) ) {
      $form_action = 'update';

      $product_query = tep_db_query("select p.products_id, pd.products_name, p.products_price, a.auctions_starting_price, a.expires_date,a.overbid_amount  from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_AUCTIONS_PRODUCTS . " a where p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = a.products_id and a.auctions_id = '" . (int)$_REQUEST['aID'] . "'");
      $product = tep_db_fetch_array($product_query);

      $aInfo = new objectInfo($product);
    } else {
      $aInfo = new objectInfo(array());

// create an array of products on auction, which will be excluded from the pull down menu of products
// (when creating a new product on auction)
      $auctions_array = array();
      $auctions_query = tep_db_query("select p.products_id from " . TABLE_PRODUCTS . " p, " . TABLE_AUCTIONS_PRODUCTS . " a where a.products_id = p.products_id");
      while ($auctions = tep_db_fetch_array($auctions_query)) {
        $auctions_array[] = $auctions['products_id'];
      }
    }
?>
      <tr><form name="new_auction" <?php echo 'action="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, tep_get_all_get_params(array('action', 'info', 'aID')) . 'action=' . $form_action, 'NONSSL') . '"'; ?> method="post"><?php if ($form_action == 'update') echo tep_draw_hidden_field('auctions_id', $_REQUEST['aID']); ?>
        <td><br><table border="0" cellspacing="0" cellpadding="2">
          <tr>
            <td class="main"><?php echo TEXT_AUCTIONS_PRODUCT; ?>&nbsp;</td>
            <td class="main"><?php echo (isset($aInfo->products_name)) ? $aInfo->products_name . ' <small>(' . $currencies->format($aInfo->products_price) . ')</small>' : tep_draw_products_pull_down('products_id', 'style="font-size:10px"', $auctions_array); echo tep_draw_hidden_field('products_price', (isset($aInfo->products_price) ? $aInfo->products_price : '')); ?></td>
          </tr>
          <tr>
            <td class="main"><?php echo TEXT_AUCTIONS_AUCTION_PRICE; ?>&nbsp;</td>
            <td class="main"><?php echo tep_draw_input_field('auctions_price', (isset($aInfo->auctions_starting_price) ? $aInfo->auctions_starting_price : '')); ?></td>
          </tr>
		  
  <tr>
            <td class="main"><?php echo TEXT_AUCTIONS_OVERBID_AMOUNT; ?>&nbsp;</td>
            <td class="main"><?php echo tep_draw_input_field('overbid_amount', (isset($aInfo->overbid_amount) ? $aInfo->overbid_amount : '')); ?></td>
          </tr>		  
          <tr>
                   
            <td class="main"><?php echo TEXT_AUCTIONS_EXPIRES_DATE; ?>&nbsp;</td>
            <td class="main"><input id="day" name ='day' type="text" size="25" <?php echo "value='";echo $aInfo->expires_date;echo "'";?> ><a href="javascript:NewCal('day','ddmmyyyy',true,24)"><img src="<?php echo DIR_WS_COMPONENT ?>includes/javascript/spiffyCal/images/btn_date2_up.gif"  height="16" border="0" alt="Pick a date"></a></td></td>
          </tr>
        </table></td>
      </tr>
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="2">
          <tr>
            <td class="main"><br><?php 
		  echo TEXT_AUCTIONS_PRICE_TIP; ?></td>
            <td class="main" align="right" valign="top"><br><?php echo (($form_action == 'insert') ? tep_image_submit('button_insert.gif', IMAGE_INSERT) : tep_image_submit('button_update.gif', IMAGE_UPDATE)). '&nbsp;&nbsp;&nbsp;<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . (isset($_REQUEST['aID']) ? '&aID=' . $_REQUEST['aID'] : '')) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>'; ?></td>
          </tr>
        </table></td>
      </form></tr>
      
      
<?php
  } else {
?>
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2" class="adminlist"><thead>
              <tr class="dataTableHeadingRow">
                <th class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td>
                <th class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_PRODUCTS_PRICE; ?></td>
                <th class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_STATUS; ?></td>
                <th class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td>
              </tr></thead>
<?php
    $auctions_query_raw = "select p.products_id, pd.products_name, p.products_price, a.auctions_id, a.auctions_starting_price, a.auctions_date_added, a.auctions_last_modified, a.expires_date, a.date_status_change, a.status,a.overbid_amount  from " . TABLE_PRODUCTS . " p, " . TABLE_AUCTIONS_PRODUCTS . " a, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = a.products_id order by pd.products_name";
    $auctions_split = new splitPageResults($_REQUEST['page'], MAX_DISPLAY_SEARCH_RESULTS, $auctions_query_raw, $auctions_query_numrows);
    $auctions_query = tep_db_query($auctions_query_raw);
    while ($auctions = tep_db_fetch_array($auctions_query)) {
      if ((!isset($_REQUEST['aID']) || (isset($_REQUEST['aID']) && ($_REQUEST['aID'] == $auctions['auctions_id']))) && !isset($aInfo)) {
        $products_query = tep_db_query("select products_image from " . TABLE_PRODUCTS . " where products_id = '" . (int)$auctions['products_id'] . "'");
        $products = tep_db_fetch_array($products_query);
        $aInfo_array = array_merge($auctions, $products);
        $aInfo = new objectInfo($aInfo_array);
      }

      if (isset($aInfo) && is_object($aInfo) && ($auctions['auctions_id'] == $aInfo->auctions_id)) {
        echo '                  <tr id="defaultSelected" class="dataTableRowSelected" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\'' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $aInfo->auctions_id . '&action=edit') . '\'">' . "\n";
      } else {
        echo '                  <tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)" onclick="document.location.href=\'' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $auctions['auctions_id']) . '\'">' . "\n";
      }
?>
                <td  class="dataTableContent"><?php echo $auctions['products_name']; ?></td>
                <td  class="dataTableContent" align="right"><span class="oldPrice"><?php echo $currencies->format($auctions['products_price']); ?></span> <span class="auctionPrice"><?php echo $currencies->format($auctions['auctions_starting_price']); ?></span></td>
                <td  class="dataTableContent" align="right">
<?php
      if ($auctions['status'] == '1') {
        echo tep_image(DIR_WS_IMAGES . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN, 10, 10) . '&nbsp;&nbsp;<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'action=setflag&flag=0&id=' . $auctions['auctions_id'], 'NONSSL') . '">' . tep_image(DIR_WS_IMAGES . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT, 10, 10) . '</a>';
      } else {
        echo '<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'action=setflag&flag=1&id=' . $auctions['auctions_id'], 'NONSSL') . '">' . tep_image(DIR_WS_IMAGES . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT, 10, 10) . '</a>&nbsp;&nbsp;' . tep_image(DIR_WS_IMAGES . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED, 10, 10);
      }
?></td>
                <td class="dataTableContent" align="right"><?php if (isset($aInfo) && is_object($aInfo) && ($auctions['auctions_id'] == $aInfo->auctions_id)) { echo tep_image(DIR_WS_IMAGES . 'icon_arrow_right.gif', ''); } else { echo '<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $auctions['auctions_id']) . '">' . tep_image(DIR_WS_IMAGES . 'icon_info.gif', IMAGE_ICON_INFO) . '</a>'; } ?>&nbsp;</td>
      </tr>
<?php
    }
?>
              <tr>
                <td colspan="4"><table border="0" width="100%" cellpadding="0"cellspacing="2">
                  <tr>
                    <td class="smallText" valign="top"><?php echo $auctions_split->display_count($auctions_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_REQUEST['page'], TEXT_DISPLAY_NUMBER_OF_AUCTIONS); ?></td>
                    <td class="smallText" align="right"><?php echo $auctions_split->display_links($auctions_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_REQUEST['page']); ?></td>
                  </tr>
<?php
  if (empty($action)) {
?>
                  <tr>
                    <td colspan="2" align="right"><?php echo '<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&action=new') . '">' . tep_image_button('button_new_product.gif', IMAGE_NEW_PRODUCT) . '</a>'; ?></td>
                  </tr>
<?php
  }
?>
<tr><td>
<?php
//	include_once(DIR_WS_MODULES.'auction_bids.php'); No such file exists as of yet
?>
</td></tr>
                </table></td>
              </tr>
            </table></td>
<?php
  $heading = array();
  $contents = array();

  switch ($action) {
    case 'delete':
      $heading[] = array('text' => '<b>' . TEXT_INFO_HEADING_DELETE_AUCTIONS . '</b>');

      $contents = array('form' => tep_draw_form('auctions', tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $aInfo->auctions_id . '&action=deleteconfirm')));
      $contents[] = array('text' => TEXT_INFO_DELETE_INTRO);
      $contents[] = array('text' => '<br><b>' . $aInfo->products_name . '</b>');
      $contents[] = array('align' => 'center', 'text' => '<br>' . tep_image_submit('button_delete.gif', IMAGE_DELETE) . '&nbsp;<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $aInfo->auctions_id) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a>');
      break;
    default:
      if (is_object($aInfo)) {
        $heading[] = array('text' => '<b>' . $aInfo->products_name . '</b>');

        $contents[] = array('align' => 'center', 'text' => '<a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $aInfo->auctions_id . '&action=edit') . '">' . tep_image_button('button_edit.gif', IMAGE_EDIT) . '</a> <a href="' . tep_href_link(FILENAME_AUCTIONS_PRODUCTS, 'page=' . $_REQUEST['page'] . '&aID=' . $aInfo->auctions_id . '&action=delete') . '">' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '</a>');
        $contents[] = array('text' => '<br>' . TEXT_INFO_DATE_ADDED . ' ' . tep_date_short($aInfo->auctions_date_added));
        $contents[] = array('text' => '' . TEXT_INFO_LAST_MODIFIED . ' ' . tep_date_short($aInfo->auctions_last_modified));
        $contents[] = array('align' => 'center', 'text' => '<br>' . tep_info_image($aInfo->products_image, $aInfo->products_name, SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT));
        $contents[] = array('text' => '<br>' . TEXT_INFO_ORIGINAL_PRICE . ' ' . $currencies->format($aInfo->products_price));
        $contents[] = array('text' => '' . TEXT_INFO_NEW_PRICE . ' ' . $currencies->format($aInfo->auctions_starting_price));
        $contents[] = array('text' => '' . TEXT_INFO_PERCENTAGE . ' ' . number_format(100 - (($aInfo->auctions_starting_price / $aInfo->products_price) * 100)) . '%');

        $contents[] = array('text' => '<br>' . TEXT_INFO_EXPIRES_DATE . ' <b>' . tep_datetime_short($aInfo->expires_date) . '</b>');
        $contents[] = array('text' => '' . TEXT_INFO_STATUS_CHANGE . ' ' . tep_datetime_short($aInfo->date_status_change));
      }
      break;
  }
  if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
    echo '            <td width="25%" valign="top">' . "\n";

    $box = new box;
    echo $box->infoBox($heading, $contents);

    echo '            </td>' . "\n";
  }
}
?>
          </tr>
        </table></td>
      </tr>
    </table></td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php');

  require(DIR_WS_INCLUDES . 'application_bottom.php');

  if (!DB_SHARED) {
    global $database, $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix;
    $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
  }
?>